package io.noties.markwon.plugin.latex.parser

import io.noties.markwon.plugin.latex.model.JLatexMathNode
import org.commonmark.node.Nodes
import org.commonmark.node.Text
import org.commonmark.parser.delimiter.DelimiterProcessor
import org.commonmark.parser.delimiter.DelimiterRun

/**
 * @since 4.3.0
 */
internal class JLatexMathDelimiterProcessor : DelimiterProcessor {

   /* protected Node parse() {
        final String latex = match(RE);
        if (latex == null) {
            return null;
        }

        final JLatexMathNode node = new JLatexMathNode();
        node.latex(latex.substring(2, latex.length() - 2));
        return node;
    }*/

    /*companion object {
        private val RE = Pattern.compile("(\\\${2})([\\s\\S]+?)\\1")
    }

    override fun specialCharacter(): Char = '$'

    override fun getPattern(): Pattern = RE

    override fun createNode(text: String): JLatexMathNode = JLatexMathNode(text.substring(2, text.length - 2))
    */
    override fun getOpeningCharacter(): Char = '$'

    override fun getClosingCharacter(): Char = '$'

    override fun getMinLength(): Int = 1

    override fun process(openingRun: DelimiterRun, closingRun: DelimiterRun): Int {
        if(openingRun.length()!=1) return 0

        // Check if the attributes can be applied - if the previous node is an Image, and if all the attributes are in
        // the set of SUPPORTED_ATTRIBUTES
        val opener = openingRun.opener
        val previousNode = opener.previous
        val content = StringBuilder()
        for (node in Nodes.between(opener, closingRun.closer)) {
            // Only Text nodes can be used for attributes
            if (node is Text) {
                content.append(node.literal)
            } else {
                // This node type is not supported, so stop here (no need to check any further ones).
                return 0
            }
        }

        previousNode.appendChild(JLatexMathNode(content.substring(2, content.length - 2)))

        return 1
    }
}

